﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace FourKill.Engine
{
    public class Ground : IPaintable
    {
        private const int SECTION_LENGTH = 20;
        private Brush _groundBrush1 = new SolidBrush(Color.FromArgb(0x22, 0xaa, 0x22));
        private Brush _groundBrush2 = new SolidBrush(Color.FromArgb(0x44, 0xaa, 0x44));

        public void Paint(IPaintableContext context)
        {
            long totalMovement = Convert.ToInt64(context.Camera.TotalMovement);
            if (totalMovement < 0) totalMovement += SECTION_LENGTH * 1000000;
            long offset = totalMovement % (SECTION_LENGTH);
            if (offset > 0) offset = (SECTION_LENGTH) - offset;
            if (offset < 0) offset = Math.Abs(SECTION_LENGTH);

            try
            {
                int lineLocation = context.ViewPort.PixelSize.Height,
                    centerLocation = lineLocation / 2,
                    prevLineLocation = lineLocation,
                    stripeSize = 1,
                    stripeIndex = 0;
                double 
                    current = 0,
                    c = context.Camera.Height + context.Camera.Z,
                    distance = 1+offset,
                    d2v = context.ViewPort.DistanceToView;

                context.BackLayer.FillRectangle(_groundBrush1, 0, centerLocation, context.ViewPort.PixelSize.Width, context.ViewPort.PixelSize.Height - centerLocation);
                while (lineLocation > centerLocation)
                {
                    prevLineLocation = lineLocation;

                    current = c / distance * d2v;
                    lineLocation = centerLocation + Convert.ToInt32(current * context.ViewPort.Scale);

                    if (lineLocation < centerLocation) continue;
                    else if (lineLocation >= context.ViewPort.PixelSize.Height)
                        lineLocation = context.ViewPort.PixelSize.Height;
                    else
                    {
                        stripeSize = prevLineLocation - lineLocation;
                        if (stripeSize == 0) break;
                        if (stripeIndex % 2 == 1)
                        {
                            context.BackLayer.FillRectangle(_groundBrush2, 0, lineLocation, context.ViewPort.PixelSize.Width, stripeSize);
                        }
                    }
                    distance += (SECTION_LENGTH/2);
                    stripeIndex++;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("***********************************");
                System.Diagnostics.Debug.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
                System.Diagnostics.Debugger.Break();
            }
        }
    }
}
